﻿using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormWeekendSetup : FormBaseDataGrid
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsWkendSetup;
        private SqlDataAdapter mdaWkendSetupUpdate;

        public FormWeekendSetup()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                cboYear.Text = DateTime.Now.Year.ToString();
                cboMonth.Text = (DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString());
                cboEmpType.SelectedIndex = 0;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Weekend Setup Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where Years = " + cboYear.Text.Trim() + " and Months = " + cboMonth.Text.Trim() + " and EmpType = "+cboEmpType.SelectedIndex.ToString()+" Order By Weekend_Date ";
                string lCondiction1 = " Years = " + cboYear.Text.Trim() + " and Months = " + cboMonth.Text.Trim() + " and EmpType = " + cboEmpType.SelectedIndex.ToString() + " Order By Weekend_Date ";

                string ls_SQL = "Select Years, Months, Weekend_Date, Hrs, On_Off, DATENAME(DW, Weekend_Date) DayOfWeek, Note, EmpType,  "
                    + "CreatedUser, UpdatedUser, CreatedDate, UpdatedDate "
                    + "From HRM_WeekendSetup "
                    + lCondiction;

                mdsWkendSetup = mCtrlGeneral.GetSelect(ls_SQL, "HRM_WeekendSetup");
                mCtrlGeneral.GetDataWithCondition(out mdaWkendSetupUpdate, "HRM_WeekendSetup", lCondiction1);

                if (mdsWkendSetup == null) return;
                //mdbg_dataGrid.AutoGenerateColumns = false;
                mdbg_dataGrid.DataSource = mdsWkendSetup;
                mdbg_dataGrid.DataMember = "HRM_WeekendSetup";


                mRowManager = (CurrencyManager)mdbg_dataGrid.BindingContext[mdsWkendSetup, "HRM_WeekendSetup"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                base.LoadMasterData();
                SetBackGroundColorDGrid();

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Weekend Setup Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Weekend Setup form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }

        public override void save()
        {
            try
            {
                if (mdsWkendSetup == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsWkendSetup.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsWkendSetup.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    } 
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaWkendSetupUpdate, ldsHasChanged, "HRM_WeekendSetup", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsWkendSetup.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                }
                else
                {
                    MessageBox.Show("Cannot save'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void cancel()
        {
            mdbg_dataGrid.Focus();
            if (mdsWkendSetup == null) return;
            mRowManager.EndCurrentEdit();
            mdsWkendSetup.RejectChanges();
            base.cancel();
        }

        #region Override Add
        public override void add()
        {
            mdbg_dataGrid.Focus();
            base.add();

            if (mdsWkendSetup != null && mdsWkendSetup.Tables[0].Rows.Count <= 0)
            {
                DataRow dr;
                DateTime dt;
                for (int i = 1; i <= DateTime.DaysInMonth(int.Parse(cboYear.Text), int.Parse(cboMonth.Text)) ; i++)
                {
                    dr = mdsWkendSetup.Tables[0].NewRow();
                    dr["Years"] = cboYear.Text.Trim();
                    dr["Months"] = cboMonth.Text;
                    dr["EmpType"] = cboEmpType.SelectedIndex;
                    dt = new DateTime(int.Parse(cboYear.Text), int.Parse(cboMonth.Text), i);
                    dr["Weekend_Date"] = dt;
                    if (dt.DayOfWeek == System.DayOfWeek.Saturday || dt.DayOfWeek == System.DayOfWeek.Sunday)
                    {
                        dr["Hrs"] = 8;
                        dr["On_Off"] = true;
                    }
                    else
                    {
                        dr["Hrs"] = 0;
                        dr["On_Off"] = false;
                    }
                    dr["DayOfWeek"] = dt.DayOfWeek;
                    dr["Note"]= "";
                    dr["CreatedUser"] = mMainForm.ms_UserID;
                    dr["CreatedDate"] = DateTime.Now;
                    mdsWkendSetup.Tables[0].Rows.Add(dr);
                }
                SetBackGroundColorDGrid();
            }
        }
        #endregion

        private void SetBackGroundColorDGrid()
        {
            int li = 0;
            DateTime dt;
            foreach (DataGridViewRow dr in mdbg_dataGrid.Rows)
            {
                dt = DateTime.Parse(dr.Cells["Weekend_Date"].Value.ToString());
                if (dt.DayOfWeek.Equals(System.DayOfWeek.Sunday))
                {
                    dr.DefaultCellStyle.BackColor = Color.Red;
                }
                else if (dt.DayOfWeek.Equals(System.DayOfWeek.Saturday))
                {
                    dr.DefaultCellStyle.BackColor = Color.Pink;
                }
                li++;
            }
        }

        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaWkendSetupUpdate, ldsDelete, "HRM_WeekendSetup", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        protected override void BaseForm_Shown(object sender, EventArgs e)
        {
            mdbg_dataGrid.Columns["Years"].Visible = false;
            SetBackGroundColorDGrid();
        }

        private void cboMonth_SelectedValueChanged(object sender, EventArgs e)
        {
            LoadData();
        }

    }
}
